"""
:synopsis: Export to Shapefiles
:authors: Riley Baird (OK), Emma Baker (OK)

"""
from pathlib import Path

import arcpy

from ng911ok.lib.misc import unwrap_to_dict
from ng911ok.lib.gdbsession import NG911Session


class ExportShapefilesTool:
    """
    Class describing an ArcGIS Python Toolbox tool: "Export to Shapefiles".
    """

    def __init__(self):
        """Define the tool (tool name is the name of the class)."""
        self.label = "Export to Shapefiles"
        self.description = "Creates a folder with the name of the input geodatabase and exports all NG911 feature classes to that folder as shapefiles."
        self.canRunInBackground = False
        self.category = "6 - Submission"

    def getParameterInfo(self):
        """Define parameter definitions"""
        params = [
            arcpy.Parameter(
                displayName="NG911 Geodatabase",
                name="gdb",
                datatype="DEWorkspace",
                parameterType="Required",
                direction="Input"
            ),
            arcpy.Parameter(
                displayName="Output Location",
                name="output_location",
                datatype="DEFolder",
                parameterType="Required",
                direction="Input"
            ),
            arcpy.Parameter(
                displayName="Respect Submit",
                name="respect_submit",
                datatype="GPBoolean",
                parameterType="Optional",
                direction="Input"
            ),
            arcpy.Parameter(
                displayName="Output Shapefiles",
                name="output_shapefiles",
                datatype="DEShapeFile",
                parameterType="Derived",
                direction="Output",
                multiValue=True
            )
        ]
        return params

    def isLicensed(self):
        """Set whether tool is licensed to execute."""
        return True

    def updateParameters(self, parameters):
        """Modify the values and properties of parameters before internal
        validation is performed.  This method is called whenever a parameter
        has been changed."""
        param_dict: dict[str, arcpy.Parameter] = {p.name: p for p in parameters}
        param_values = unwrap_to_dict(parameters)
        output_location: Path | None = Path(x) if (x := param_values["output_location"]) else None
        # output_folder_name: str | None = param_values["output_folder_name"]
        # output_folder_path: Path | None = output_location / output_folder_name if output_location and output_folder_name else None
        #
        # if output_folder_path and output_folder_path.exists():
        #     param_dict["output_folder_name"].setErrorMessage(f"A folder with this name ({str(output_folder_path)}) already exists.")
        # else:
        #     param_dict["output_folder_name"].clearMessage()

    def updateMessages(self, parameters):
        """Modify the messages created by internal validation for each tool
        parameter.  This method is called after internal validation."""
        return

    def execute(self, parameters, messages):
        """The source code of the tool."""
        param_dict: dict[str, arcpy.Parameter] = {p.name: p for p in parameters}
        param_values = unwrap_to_dict(parameters)
        gdb = Path(param_values["gdb"])
        output_location = Path(param_values["output_location"])
        respect_submit = bool(param_values["respect_submit"])

        with NG911Session(gdb, respect_submit) as session:
            shp_paths = session.to_shapefiles(output_location)
        param_dict["output_shapefiles"].values = [str(x) for x in shp_paths]


if __name__ == "__main__":
    raise Exception("This module is a dependency of an ArcGIS Python Toolbox and should not be executed directly.")
